package xml;

import java.awt.Color;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;

import logger.Logger;

import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;


public class SettingsProvider {

	public static final SettingsProvider INSTANCE = new SettingsProvider();
	private HashMap<String, String> settings = new HashMap<>();
	
	private SettingsProvider()
	{
		
		try
		{
			File f = new File("settings.xml");
			if(!f.exists())
			{
				XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
				sortie.output(new Document(new Element("Reglages")), new FileOutputStream("settings.xml"));
				//f.createNewFile();
			}
			
			SAXBuilder sxb = new SAXBuilder();
			Document doc = sxb.build(f);
			for(Element el : doc.getRootElement().getChildren())
			{
				String nom = el.getAttributeValue("Nom");
				String val = el.getAttributeValue("Valeur");
				settings.put(nom,val);
			}
			
		}
		catch(Exception ex)
		{
			Logger.INSTANCE.logError(ex);
			ex.printStackTrace();
		}
		
	}
	
	public boolean haveParam(String nom)
	{
		return settings.containsKey(nom);
	}
	
	public String getParam(String nom)
	{
		if(settings.containsKey(nom))
			return settings.get(nom);
		return "";
	}
	
	public void setParam(String nom, String valeur)
	{
		settings.put(nom, valeur);
		saveAll();
	}
	
	
	public void saveAll()
	{
		Element newRoot = new Element("Reglages");
		
		for(String nom : settings.keySet())
		{
			Element impE = new Element("Reglage");
			impE.setAttribute(new Attribute("Nom", nom));
			impE.setAttribute(new Attribute("Valeur", settings.get(nom)));
			newRoot.addContent(impE);
		}
		
		enregistre(newRoot, "settings.xml");
	}
	
	private static void enregistre(Element racine, String fichier)
	{
	   try
	   {
	      XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
	      sortie.output(new Document(racine), new FileOutputStream(fichier));
	   }
	   catch (java.io.IOException e){
		   Logger.INSTANCE.logError(e);
		   e.printStackTrace();
	   }
	}
}

